import time
import datetime
from selenium.common import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
import requests
import json
from datetime import date
import os
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


def openWEB(auctionId):
    url = f'https://paipai.jd.com/auction-detail/{auctionId}'
    today = date.today().strftime("%Y-%m-%d")
    filename = f"{today}_cookie.json"
    options = {'performance': 'ALL'}
    chrome_options = webdriver.ChromeOptions()
    chrome_options.set_capability('goog:loggingPrefs', options)
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(url)
    if os.path.exists(filename):
        with open(filename, "r") as f:
            cookies = json.load(f)
            for cookie in cookies:
                driver.add_cookie(cookie)
            driver.refresh()
    else:
        print('今天没有登录过，请先扫码登录')
        login_button = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "pp-shortcut__btn-login")))
        if login_button:
            login_button.click()
            print('点击了登录按钮')
        scan_button = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="content"]/div[2]/div[1]/div/div/div[2]/div[1]/a')))
        if scan_button:
            scan_button.click()
            print('点击了扫码登录')
        login_success = WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CLASS_NAME, "pp-shortcut__user-menu")))
        if login_success:
            print('扫码登录成功')
            with open(filename, "w") as file:
                json.dump(driver.get_cookies(), file)
    time.sleep(30)
    queryTimes = 1  # 最后一秒查询N次价格后出价
    doBuying = False
    str_count_down = ''
    while True:
        try:
            element = driver.find_element(By.CSS_SELECTOR, "#J-count-down")
            hours, minutes, seconds = element.text.split(" ")[0::2]
            hours = int(hours)
            minutes = int(minutes)
            seconds = int(seconds)
            if str_count_down != f'剩余时间{minutes * 60 + seconds}秒':
                str_count_down = f'剩余时间{minutes * 60 + seconds}秒'
                print(str_count_down)
            if hours == 0 and minutes == 0 and seconds == 1 and queryTimes != 0:
                print('最后1秒')
                # time.sleep(0.0001)
                currentPrice = queryInfo(auctionId)
                queryTimes -= 1
                print(f'最新价格【{currentPrice}】第{queryTimes}次')
                if queryTimes == 0:
                    if maxPrice > currentPrice:
                        if not doBuying:
                            toBuy(driver, int(currentPrice + 1))
                            doBuying = True
                    else:
                        print('超过理想价格', maxPrice)
        except NoSuchElementException:
            print('竞拍结束')
            time.sleep(100)
            break


def toBuy(driver, price):
    el_input = driver.find_element(By.CLASS_NAME, 'el-input__inner')
    driver.execute_script("arguments[0].value = '';", el_input)
    el_input.send_keys(price)
    print(f'您出的价格是{price}')
    buy_button = driver.find_element(By.ID, 'InitCartUrl')
    buy_button.click()
    time.sleep(100)


def queryInfo(auctionId):
    api_cookies = {
        '__jdv': '148612534|direct|-|none|-|1695697289453',  #
        '__jdu': '16956972894521174667777',
        'pinId': 'GxstBDmMt8n5uDzDcSdDTFzYwimK3aJR',
        'ceshi3.com': '201',
        '_tp': 'hQYhBgBb4UWLJYwMfAVT5Unc0i7bTO07Rrb7hDSsEZA%3D',
        'logining': '1',
        '_pst': '107005678-35833035',
        '3AB9D23F7A4B3C9B': '5LRPWIVTC572DREGDG5NBQ3MJAA2DAN5VYOER73FVAVX4DGBS4LP3H7ZWEUWKALQIQQCTAV3OYEG743QSRBRULMP4A',
        'wlfstk_smdl': 'h4e1p8ktl8wbarn339fxs8qda5fzkk52',
        'TrackID': '109WGmtHJonCvliz64heaAZTKw0yARiWvKiluk0P3X-CAFNnYBfQMBndsTUVWlTB4wWPhxhRJVjHU_RRJ05U85TAElWLm3-2gLUTHDTafGv-M4KhCvwMDBL3_SzvkWska',
        'thor': '470AEFF9A67178BF39F0441D9437073A98F1E5A58D3C4A3C70D8B5B3238AFF8805A0F67D22B2DA4F5816410CDF010B30AA5E0B035AE719FDC63427AC89BFC74CC9F7C842ACAE9CEFAFAA3DD4429A4EB7C0C41B72C559B1A305910B3D79419F2DD81725D0EF9F137E16847F0E437F5D48434FFA5DCF6F3AC065140647314B19FD56306DC011BEA27C7A728AE95EA8E1F742B95CD4886711B228B4C1DB86671D17',
        'flash': '2_91FU11fU0USVe_uRFuK9phPhq6TfaiicVKOCWmtUT0QX1K8rEP-kpmzTn2BAyg5Bazn61mFgV-QZvw54dyNpphYdLcjmhqpM860tx6bfXYq*',
        'pin': '107005678-35833035',
        'unick': '%E5%BC%A0%E5%A4%A7%E5%A4%B4123',
        '__jdc': '148612534',
        '__jda': '148612534.16956972894521174667777.1695697289.1695697289.1695710809.2',
        '3AB9D23F7A4B3CSS': 'jdd035LRPWIVTC572DREGDG5NBQ3MJAA2DAN5VYOER73FVAVX4DGBS4LP3H7ZWEUWKALQIQQCTAV3OYEG743QSRBRULMP4AAAAAMK2A6Y76YAAAAACLPMROHQKHMX74X',
        '_gia_d': '1',
        '__jdb': '148612534.3.16956972894521174667777|2.1695710809',
    }
    headers = {
        'authority': 'api.m.jd.com',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'origin': 'https://paipai.jd.com',
        'referer': 'https://paipai.jd.com/',
        'sec-ch-ua': '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-site',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
        'x-referer-page': 'https://paipai.jd.com/auction-detail/382418791',
        'x-rp-client': 'h5_1.0.0',
    }
    time = int(datetime.datetime.now().timestamp() * 1000)
    response = requests.get(
        url=f'https://api.m.jd.com/api?functionId=paipai.auction.current_bid_info&t={time}&appid=paipai_sale_pc&client=pc&loginType=3&uuid=1694401699552982070389&x-api-eid-token=jdd035LRPWIVTC572DREGDG5NBQ3MJAA2DAN5VYOER73FVAVX4DGBS4LP3H7ZWEUWKALQIQQCTAV3OYEG743QSRBRULMP4AAAAAMK2A6Y76YAAAAACLPMROHQKHMX74X&body=%7B%22auctionId%22:{auctionId}%7D',
        cookies=api_cookies,
        headers=headers,
    )
    res_json = response.json()
    if res_json['code'] == 0:
        result = res_json['result']
        if result['code'] == 200:
            data = result['data']
            if data:
                info = data[f'{auctionId}']
                currentPrice = info['currentPrice']
                return currentPrice


if __name__ == '__main__':
    maxPrice = 449  # 能接受的最高价格
    auctionId = 383083254  # 商品id
    openWEB(auctionId)
